package com.itheima.controller;


import com.itheima.code.ValidateCodeUtils;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pub.MessageConstant;
import com.itheima.pub.RedisMessageConstant;
import com.itheima.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    RedisTemplate redisTemplate;

    @Reference
    OrderService orderService;

    @RequestMapping("addOrder")
    public Result addOrder(@RequestBody Map map){
        try {
            String validateCode =(String) map.get("validateCode");
            if (StringUtils.isNotBlank(validateCode)){
                String telephone = (String) map.get("telephone");
                String  redisCode = (String) redisTemplate.opsForValue().get(RedisMessageConstant.SENDTYPE_LOGIN + telephone);
                if (StringUtils.isNotBlank(redisCode)){
                    if (validateCode.equals(redisCode)){
                        Order order = orderService.addOrder(map);
                        return new Result(true,"预约成功",order);
                    }else {
                        return new Result(false,"验证码错误");
                    }
                }else {
                    return new Result(false,"验证码过期");
                }
            }else {
                return new Result(false, "验证码非法");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
    }

    @RequestMapping("findOrderById")
    public Result findOrderById(@RequestParam("id")Integer id){
        try {
            Map map = orderService.findMemberNameAndSetmealNameAndOrderById(id);
            return new Result(true,"查询信息成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询信息失败");
        }
    }
}
